package edu.cth.scrabbit.server.core.network;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import edu.cth.scrabbit.server.core.ServerModel;
import edu.cth.scrabbit.server.core.ServerPlayer;


/**
 * 
 * A class that makes it possible for the server to communicate with the clients
 * @author Anders Jonsson, Marcus Harryson
 * 
 */
public class ServerListener extends Thread implements IServerListener {
	private ServerSocket serverSocket;
	private Boolean isListening = false;
	
	/**
	 * Constructor for a new ServerSocket
	 * 
	 * @param port, the port to which the serversocket will be listening
	 */
	public ServerListener(int port) {
		super("ServerListener");
		try {
			serverSocket = new ServerSocket(port);
		} catch (IOException e) {
			System.out.println("Port: " + port + " busy");
			e.printStackTrace();
		}
	}

	@Override
	public void listenToClient() {
		isListening = true;
		// listening for clients to connect with
		while (isListening) {
			Socket clientSocket = null;
			try {
				// Connects a player if the game isn't full
				clientSocket = serverSocket.accept();
				PlayerThread thread = new PlayerThread(clientSocket);
				ServerPlayer p = new ServerPlayer(thread);
				ServerModel.getInstance().addPlayer(p);
				if(ServerModel.getInstance().wasPlayerAdded()){
					thread.start();
				} else{
					System.out.println("Game already full");
				}
			} catch (IOException e) {
				System.out.println("Could not accept connection");
				e.printStackTrace();
			}
			
		}
		
		// Clean-up:
		try {
			serverSocket.close();
		} catch (IOException e) {
			System.out.println("Could not close the socket");
			e.printStackTrace();
		}
	}
	
	public void run() {
		listenToClient();
	}
}